<div id="content_worktimes" name="content_worktimes" style="padding-left:0px"><br><h2>Arbeitsplanung</h2><ul>
    <li><a href="/worktime">Arbeitsplanung</a></li>
</ul><hr><br><b>Arbeitstermine und Verfügbarkeiten</b><br>Um einen neuen Eintrag zu erstellen oder einen bereits vorhandenen zu editieren, markieren Sie bitte ein Kästchen in dem Kalender.<?php
$this->headScript()->appendFile('/libs/jquery.weekcalendar.js');
$this->headScript()->appendFile('/libs/date.js');
$this->headScript()->appendFile('/libs/jquery-ui-i18n.js');
$this->headLink()->appendStylesheet('/libs/css/smoothness/jquery-ui-1.8.11.custom.css');
$this->headLink()->appendStylesheet('/libs/css/jquery.weekcalendar.css');
$this->headLink()->appendStylesheet('/libs/calendar_skins/default.css');
$this->headLink()->appendStylesheet('/libs/calendar_skins/gcalendar.css');
$this->headLink()->appendStylesheet('/libs/css/event.css');
?><br /><br />
  <script type="text/javascript">

  var updateURLToken = "/worktime/update/id/";
  var createURLToken = "/worktime/new";

  function postToUrl(path, params, method) {
      method = method || "post";
      var form = document.createElement("form");
      form.setAttribute("method", method);
      form.setAttribute("action", path);
      for(var key in params) {
          if(params.hasOwnProperty(key)) {
              var hiddenField = document.createElement("input");
              hiddenField.setAttribute("type", "hidden");
              hiddenField.setAttribute("name", key);
              hiddenField.setAttribute("value", params[key]);
              form.appendChild(hiddenField);
          }
      }
      document.body.appendChild(form);
      form.submit();
  }

  (function($) {

    var d = new Date();
    d.setDate(d.getDate() - d.getDay());
    var year = d.getFullYear();
    var month = d.getMonth();
    var day = d.getDate();
    <?php 
        $__bStartDate = false;
        $sA = array();
        if(count($this->calendarStatusArray)) {
            $sA = $this->calendarStatusArray;               
            if(isset($sA['startDate']))
                if(strlen($sA['startDate'])) {
                    $__bStartDate = true;
                    $_startDate = $sA['startDate'];
                    $_startDate = substr($_startDate,0,10);
                    $_y = (int)strval(substr($_startDate,0,4));
                    $_m = (int)strval(substr($_startDate,5,2));
                    $_d = (int)strval(substr($_startDate,8,2));
                    
                    print "var __startDate = new Date(); __startDate.setFullYear(".$_y.", ".($_m-1).", ".$_d."); __startDate.setDate(__startDate.getDate()+1);";
                }
        }
    
    ?>

    function updateMessage() {
      var dataSource = $('#data_source').val();
      $('#message').fadeOut(function() {
	    var sa1="Kalender mit einem Slot pro Tag.";
	    var sa2="Kalender mit 6 Slots pro Tag.";
        if (dataSource === '1') {
          $('#message').text(sa1);
        } else if(dataSource === '2') {
          $('#message').text(sa2);
        } else {
          $('#message').text(sa1);
        }
        $(this).fadeIn();
      });
    }

    $(document).ready(function() {    
        var $calendar = $('#calendar').weekCalendar({
	    timeslotsPerHour: 4,
        timeslotHeight: 20,
        <?php 
        
            if($__bStartDate) {
                print "date: __startDate,";
            }
        
	    ?>
        
        scrollToHourMillis : 500,
	    use24Hour: true,
	    hourLine: true,
	    users: 1,
        defaultFreeBusy: {free: true},
        displayFreeBusys: true,
	    allowCalEventOverlap: true,
	    overlapEventsSeparate: true,
        height: function($calendar){
          return $(window).height() - $('h1').outerHeight(true);
        },
        sendCallByEvent : function(calEvent, eventType) {
            var reqURL="worktime/";
            $.getJSON(reqURL, {
              'id': calEvent.id,
              'date_from': calEvent.start.toString('dd.MM.yyyy HH:mm'),
              'date_to': calEvent.end.toString('dd.MM.yyyy HH:mm'),
              'event': eventType
          },null);             
        },        
        checkEvent : function(calEvent) {
          if(calEvent.start.toString('dd.MM.yyyy')!=calEvent.end.toString('dd.MM.yyyy')) {
              window.location.href=updateURLToken+calEvent.id;
              return false;
          } /*else if($('#data_source_3').val()=='wt') {
              window.location.href=updateURLToken+calEvent.id;
              return false;
          }*/ else {
            return true;
          }
        },
	    eventClick : function(calEvent, element, freeBusyManager, $calendar, DomEvent) {
	       window.location.href=updateURLToken+calEvent.id;
	    },
        eventRender : function(calEvent, $event) {
           if (calEvent.end.getTime() < new Date().getTime()) {
             $event.css('backgroundColor', '#aaa');
             $event.find('.wc-time').css({
               backgroundColor: '#999',
               border:'1px solid #888'
             });
           } else {
             if($('#data_source_3').val()=='av') {
             $event.css('backgroundColor', '#11cc11');
             $event.find('.wc-time').css({
               backgroundColor: '#119911',
               border:'1px solid #11aa11'
             });                
             }
           }
        },
        /*eventDrop : function(calEvent, oldCalEvent, $event) { 
          var reqURL="worktime/";
          if(!this.checkEvent(oldCalEvent)) {
              return;
          } else {
              $.getJSON(reqURL, {
                'id': calEvent.id,
                'date_from': calEvent.start.toString('dd.MM.yyyy HH:mm'),
                'date_to': calEvent.end.toString('dd.MM.yyyy HH:mm'),
                'event': "eventDrop",
                'modus': $('#data_source_3').val()
              },function(data) {
                if(data['success']==false) {
                    alert(data['message']);
                    $calendar.weekCalendar('refresh');
                }
              });
          }
        }, 
	    eventResize : function(newCalEvent, oldCalEvent, element){
          var reqURL="worktime/";
          if(!this.checkEvent(oldCalEvent)) {
              return;
          } else {
              $.getJSON(reqURL, {
                'id': oldCalEvent.id,
                'date_from': newCalEvent.start.toString('dd.MM.yyyy HH:mm'),
                'date_to': newCalEvent.end.toString('dd.MM.yyyy HH:mm'),
                'event': "eventResize",
                'modus': $('#data_source_3').val()
              },function(data) {
                if(data['success']==false) {
                    alert(data['message']);
                    $calendar.weekCalendar('refresh');
                }
              });
          }              
	    },*/
        eventDrop : function(calEvent, oldCalEvent, $event) { 
	       postToUrl(updateURLToken+calEvent.id,{
                                     date_from:calEvent.start.toString('dd.MM.yyyy HH:mm'),
                                     date_to:calEvent.end.toString('dd.MM.yyyy HH:mm'),
                                     modus:$('#data_source_3').val(),
                                     id: oldCalEvent.id,
                                     Mitarbeiter: oldCalEvent.personId});
        }, 
	    eventResize : function(calEvent, oldCalEvent, $event){
	       postToUrl(updateURLToken+calEvent.id,{
                                     date_from:calEvent.start.toString('dd.MM.yyyy HH:mm'),
                                     date_to:calEvent.end.toString('dd.MM.yyyy HH:mm'),
                                     modus:$('#data_source_3').val(),
                                     id: oldCalEvent.id,
                                     Mitarbeiter: oldCalEvent.personId});        
	    },        
        eventNew : function(calEvent, $event, FreeBusyManager, calendar) {
          var isFree = true;
          $.each(FreeBusyManager.getFreeBusys(calEvent.start, calEvent.end), function() {
                if (
                  this.getStart().getTime() != calEvent.end.getTime()
                  && this.getEnd().getTime() != calEvent.start.getTime()
                  && !this.getOption('free')
                ){
                  isFree = false;
                }
          });

          if (!isFree) {
            alert('looks like you tried to add an event on busy part !');
            $(calendar).weekCalendar('removeEvent',calEvent.id);
            return false;
          }
                   
	      //postToUrl('/worktime/new',{date_from:calEvent.start.toString('dd.MM.yyyy HH:mm'),date_to:calEvent.start.addHours(1).toString('dd.MM.yyyy HH:mm')});
	      var sFrom=calEvent.start.toString('dd.MM.yyyy HH:mm');
	      var sTo=calEvent.end.toString('dd.MM.yyyy HH:mm');
	      if(sFrom==sTo) {
              sTo=calEvent.start.addHours(1).toString('dd.MM.yyyy HH:mm');
	      }
	      postToUrl(createURLToken,{date_from:calEvent.start.toString('dd.MM.yyyy HH:mm'),
                                    date_to:calEvent.end.toString('dd.MM.yyyy HH:mm'),
                                    modus:$('#data_source_3').val(),
                                    Mitarbeiter:$('#data_source_2').val()});
          calEvent.id = calEvent.userId +'_'+ calEvent.start.getTime();
          $(calendar).weekCalendar('updateFreeBusy', {
                userId: calEvent.userId,
                start: calEvent.start,
                end: calEvent.end,
                free:false
          });
        },
        data: function(start, end, callback) { 
          var reqURL="",reqURLDefault="worktime/";
          var dataSource = $('#data_source').val();
          if (dataSource === '1') {
              reqURL=reqURLDefault;
          } else if(dataSource === '2') {
              reqURL=reqURLDefault;            
          } else {
              reqURL=reqURLDefault;
          }
          $.getJSON(reqURL, {
              startDate: start.toISOString(),
              endDate: end.toISOString(),
              numUsers: $('#data_source').val(),
              idWorker: $('#data_source_2').val(),
              modus: $('#data_source_3').val()
          }, function(result) {
            callback(result);
          });
        },
        showAsSeparateUser: false, 
        displayOddEven: true,
        displayFreeBusys: true,
        daysToShow: 5,
        switchDisplay: {'ein Tag': 1, '3 Tage': 3, 'Arbeitswoche': 5, 'Woche': 7},
        headerSeparator: ' ',
        useShortDayNames: true,
        // I18N
        firstDayOfWeek: $.datepicker.regional['de'].firstDay,
        shortDays: $.datepicker.regional['de'].dayNamesShort,
        longDays: $.datepicker.regional['de'].dayNames,
        shortMonths: $.datepicker.regional['de'].monthNamesShort,
        longMonths: $.datepicker.regional['de'].monthNames,
        dateFormat: 'd. F y'
      });     

      $('#data_source').change(function() {
        //users=['Slot 1', 'Slot 2', 'Slot 3', 'Slot 4', 'Slot 5', 'Sonstiges'];
        //$('#calendar').users = users;
        $calendar.weekCalendar('refresh');
        updateMessage();
      });

      $('#data_source_2').change(function() {
        $calendar.weekCalendar('refresh');
      });
      
      $('#data_source_3').change(function() {
        $calendar.weekCalendar('refresh');
      });
      
      updateMessage();
      
    });
    
  })(jQuery);
  
  </script>
<div id="event_index">
  <div id="message" class="ui-corner-all"></div>
  <div id="calendar_selection" class="ui-corner-all">
    <strong>Kalenderansicht: </strong>
    <select id="data_source">
      <option value=""<?php if(isset($sA['numUsers'])) {if(!strval($sA['numUsers'])) print ' selected="selected"';} ?>>Kalendertyp wählen</option>
      <option value="1"<?php if(isset($sA['numUsers'])) {if(strval($sA['numUsers'])==1) print ' selected="selected"';} ?>>Ein Slot/Tag</option>
      <option value="2"<?php if(isset($sA['numUsers'])) {if(strval($sA['numUsers'])==2) print ' selected="selected"';} ?>>6 Slots/Tag</option>
    </select>
  </div>
  <div id="calendar_selection_2" style="font-size:12px;height:25px;padding:5px;background-color:#AAAAEE" align="right">
    <strong>Modus: </strong>
    <select id="data_source_3">
        <option value="wt"<?php if(isset($sA['modus'])) {if($sA['modus']=="wt") print ' selected="selected"';} ?>>Arbeitszeiten</option>
        <option value="av"<?php if(isset($sA['modus'])) {if($sA['modus']=="av") print ' selected="selected"';} ?>>Verfügbarkeiten</option>
    </select>&nbsp;&nbsp;&nbsp;&nbsp;
    <strong>Mitarbeiter: </strong>
    <select id="data_source_2"><?php if($this->bIsAdmin) print'<option value="0"';?><?php
         if(isset($sA['idWorker']) && $this->bIsAdmin) {
                if(strval($sA['idWorker'])==0) 
                    print ' selected="selected"';
         } ?><?php 
         if($this->bIsAdmin)
            print'>Alle</option>';?><?php
      $__idW = 0;
      if(isset($sA['idWorker']))
        $__idW = $sA['idWorker'];
      foreach($this->aWorkers as $aW) {
          if($this->bIsAdmin) {
              print '<option value="'.$aW['id'].'"'.(($__idW==$aW['id']) ? ' selected="selected"':'').'>'.$aW['forename'].' '.$aW['surname'].'</option>';
          } else if(!$this->bIsAdmin) {
              if($aW['id']==strval($this->userId_)) {
                  print '<option value="'.$aW['id'].'"'.(($__idW==$aW['id']) ? ' selected="selected"':'').'>'.$aW['forename'].' '.$aW['surname'].'</option>';
                  break;
              }
          }
      }
    ?></select>
  </div>
  <div id="calendar"></div> 
</div>
</div>
